package com.feeyo.monitor.service.imp;

import java.math.BigDecimal;
import java.util.*;

import com.feeyo.monitor.cache.CacheCons;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.StringRedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.stereotype.Service;

import com.feeyo.monitor.cache.CacheManager;
import com.feeyo.monitor.domain.Vehicle;
import com.feeyo.monitor.mapper.VehicleMapper;
import com.feeyo.monitor.service.VehicleService;

@Service
public class VehicleServiceImp implements VehicleService {

	@Autowired
	VehicleMapper vehicleMapper;
	@Autowired
	CacheManager cacheManager;

	
	@Override
	public List<Vehicle> selectByUser(Map param) {
        List<Vehicle> result = vehicleMapper.selectByUser(param);
//        for (Vehicle vehicle : result) {
//            Object lon = cacheManager.hashGet(CacheCons.VEHICLE_REALTIME_STATUS + vehicle.getId(),"lon");
//            if (lon != null)
//                vehicle.setLon(Double.parseDouble(lon.toString()));
//            Object lat = cacheManager.hashGet(CacheCons.VEHICLE_REALTIME_STATUS + vehicle.getId(),"lat");
//            if (lat != null)
//                vehicle.setLat(Double.parseDouble(lat.toString()));
//        }

        RedisCallback<Object> pipelineCallback  = connection ->  {
                StringRedisConnection stringRedisConn = (StringRedisConnection)connection;
                result.forEach(t->{
                    Vehicle vehicle = (Vehicle)t;
                    stringRedisConn.hGet(CacheCons.VEHICLE_REALTIME_STATUS + vehicle.getId(),"lon");
                    stringRedisConn.hGet(CacheCons.VEHICLE_REALTIME_STATUS + vehicle.getId(),"lat");
                    stringRedisConn.hGet(CacheCons.VEHICLE_REALTIME_STATUS + vehicle.getId(),"time");
                    stringRedisConn.hGet(CacheCons.VEHICLE_REALTIME_STATUS + vehicle.getId(),"spd");
                    stringRedisConn.hGet(CacheCons.VEHICLE_REALTIME_STATUS + vehicle.getId(),"dire");
                });
                return null;
        };

       List<Object> lonlatArr = cacheManager.executePipeline(pipelineCallback);
       int resultSize = result.size();
       for(int i=0;i<resultSize;i++){
           Vehicle v = result.get(i);
           if(lonlatArr.get(i*5) != null) {
               v.setLon(Double.parseDouble((String) lonlatArr.get(i * 5)));
               v.setLat(Double.parseDouble((String) lonlatArr.get(i * 5 + 1)));
               String time = (String) lonlatArr.get(i * 5 + 2);
               if(time.contains("E9")) {
                   double e9 = Double.parseDouble(time);
                   BigDecimal bd=new BigDecimal(e9);
                   v.setTime(bd.longValue());
               }else {
                   if("0.0".equals(time))
                       continue;
                   try {
                       v.setTime(Long.parseLong(time));
                   }catch (Exception e){
                       System.out.println("设备时间转换错误");
                       System.out.println("vehid->"+v.getId());
                       e.printStackTrace();
                   }
               }
               v.setSpeed(Float.parseFloat((String) lonlatArr.get(i * 5 + 3)));
               v.setDirection(Float.parseFloat((String)lonlatArr.get(i*5 + 4)));
           }
       }

	   return result;
	}

    @Override
    public List<Map> selectIdByUser(Map param) {
        return vehicleMapper.selectIdByUser(param);
    }

    @Override
	public List<Map> selectAll() {
		return vehicleMapper.selectAll();
	}

    @Override
    public Integer selectCount(Map param) {
        return vehicleMapper.selectCount(param);
    }

    @Override
	public PageInfo selectByPage(Map param,int pageNumber,int pageSize) {
		Page<Map> page = PageHelper.startPage(pageNumber, pageSize);
		List<Map> result = vehicleMapper.selectByPage(param);
        for(Map item : result){
            String vehicleId = (String)item.get("id");
            String stime = (String)cacheManager.hashGet("veh:rt:"+vehicleId,"time");
            if (stime == null) {
                item.put("lastTime",1L);
                continue;
            }
            long time = -1;
            if(stime.contains("E9")) {
                double e9 = Double.parseDouble(stime);
                BigDecimal bd=new BigDecimal(e9);
                time = bd.longValue();
            }else {
                if("0.0".equals(stime))
                    continue;
                time = Long.parseLong(stime);
            }
            item.put("lastTime",time);
        }
        PageInfo pi = new PageInfo(result);
		return pi;
	}

	@Override
	public Vehicle selectByPrimaryKey(String id) {
		return vehicleMapper.selectByPrimaryKey(id);
	}

	@Override
	public int insert(Vehicle record) {
		return vehicleMapper.insert(record);
	}

	@Override
	public int updateByPrimaryKeySelective(Vehicle record) {
		return vehicleMapper.updateByPrimaryKeySelective(record);
	}

	@Override
	public int updateDeleteStatus(String vehicleId) {
		return vehicleMapper.updateDeleteStatus(vehicleId);
	}

    @Override
    public int updateVehicleStatus(Map param) {
        return vehicleMapper.updateVehicleStatus(param);
    }

    @Override
    public String selectDevidByNumber(String number) {
        return vehicleMapper.selectDevidByNumber(number);
    }

    @Override
    public List<Map> selectExportAll() {
        List<Map> result = vehicleMapper.selectByPage(new HashMap());
        for(Map item : result){
            String vehicleId = (String)item.get("id");
            String stime = (String)cacheManager.hashGet("veh:rt:"+vehicleId,"time");
            if (stime == null) {
                item.put("lastTime",1L);
                continue;
            }
            long time = -1;
            if(stime.contains("E9")) {
                double e9 = Double.parseDouble(stime);
                BigDecimal bd=new BigDecimal(e9);
                time = bd.longValue();
            }else
                time = Long.parseLong(stime);
            item.put("lastTime",time);
        }

        Collections.sort(result, new Comparator<Map>() {
            @Override
            public int compare(Map o1, Map o2) {
                if ((Long)o1.get("lastTime") > (Long)o2.get("lastTime"))
                    return -1;
                else if ((Long)o1.get("lastTime") == (Long)o2.get("lastTime"))
                    return 0;
                else
                    return 1;
            }
        });
        return result;
    }

    @Override
    public List<Map> selectExportPage(Map param, int pageNumber, int pageSize) {
        Page<Map> page = PageHelper.startPage(pageNumber, pageSize);
        List<Map> result = vehicleMapper.selectByPage(param);
        PageInfo pi = new PageInfo(result);
        List<Map> resultP = pi.getList();
        for(Map item : resultP){
            String vehicleId = (String)item.get("id");
            String stime = (String)cacheManager.hashGet("veh:rt:"+vehicleId,"time");
            if (stime == null) {
                item.put("lastTime",1L);
                continue;
            }
            long time = -1;
            if(stime.contains("E")) {
                double e9 = Double.parseDouble(stime);
                BigDecimal bd=new BigDecimal(e9);
                time = bd.longValue();
            }else
                time = Long.parseLong(stime);
            item.put("lastTime",time);
        }

        Collections.sort(resultP, new Comparator<Map>() {
            @Override
            public int compare(Map o1, Map o2) {
                if ((Long)o1.get("lastTime") > (Long)o2.get("lastTime"))
                    return -1;
                else if ((Long)o1.get("lastTime") == (Long)o2.get("lastTime"))
                    return 0;
                else
                    return 1;
            }
        });
        return resultP;
    }

}
